package com.smartfactory.sail.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartfactory.sail.dto.InStorageInfo;
import com.smartfactory.sail.entity.*;
import com.smartfactory.sail.entity.enums.*;
import com.smartfactory.sail.mapper.*;
import com.smartfactory.sail.service.*;
import com.smartfactory.sail.utils.CommonUtils;
import com.smartfactory.sail.vo.storage.ItemStorageInfo;
import com.smartfactory.sail.vo.storageinspection.AddStorageInRecordReq;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 仓库当前情况/每种物品总情况 服务实现类
 * </p>
 *
 * @author 王巨壁
 * @since 2019-08-07
 */
@Service
public class StorageCurrentInfoServiceImpl extends ServiceImpl<StorageCurrentInfoMapper, StorageCurrentInfo> implements IStorageCurrentInfoService {

    private StorageCurrentInfoMapper storageCurrentInfoMapper;
    private ItemMapper itemMapper;
    private IPurchaseRecordService iPurchaseRecordService;
    private IItemInspectioncriteriaService iItemInspectioncriteriaService;
    private StorageRecordMapper storageRecordMapper;
    private PurchaseMapper purchaseMapper;
    private StorageInspectionRecordMapper storageInspectionRecordMapper;
    private OrderItemMapper orderItemMapper;
    private IStorageInspectionService iStorageInspectionService;
    private IStorageInspectionRecordService iStorageInspectionRecordService;
    private ItemMaterialMapper itemMaterialMapper;
    private OrderMapper orderMapper;

    public StorageCurrentInfoServiceImpl(StorageCurrentInfoMapper storageCurrentInfoMapper, ItemMapper itemMapper, IPurchaseRecordService iPurchaseRecordService, IItemInspectioncriteriaService iItemInspectioncriteriaService, StorageRecordMapper storageRecordMapper, PurchaseMapper purchaseMapper, StorageInspectionRecordMapper storageInspectionRecordMapper, OrderItemMapper orderItemMapper, IStorageInspectionService iStorageInspectionService, IStorageInspectionRecordService iStorageInspectionRecordService, ItemMaterialMapper itemMaterialMapper, OrderMapper orderMapper) {
        this.storageCurrentInfoMapper = storageCurrentInfoMapper;
        this.itemMapper = itemMapper;
        this.iPurchaseRecordService = iPurchaseRecordService;
        this.iItemInspectioncriteriaService = iItemInspectioncriteriaService;
        this.storageRecordMapper = storageRecordMapper;
        this.purchaseMapper = purchaseMapper;
        this.storageInspectionRecordMapper = storageInspectionRecordMapper;
        this.orderItemMapper = orderItemMapper;
        this.iStorageInspectionService = iStorageInspectionService;
        this.iStorageInspectionRecordService = iStorageInspectionRecordService;
        this.itemMaterialMapper = itemMaterialMapper;
        this.orderMapper = orderMapper;
    }

    @Override
    public Integer getStorageCurrentSize(Wrapper<StorageCurrentInfo> queryWrapper) {


        return null;
    }

    @Override
    public List<StorageCurrentInfo> getItemCurrentSize(Long orderId) {
        return storageCurrentInfoMapper.getItemCurrentSize(orderId);
    }

    @Override
    public ItemStorageInfo getStorageInfoByItemId(Long itemId, Integer storageType) {

        //库存数量  原料名称  料号  图纸编号  原料名称 状态  材质  领料上限  库存下限  库存上限  检测标准  入库明细  原料图纸
        //item 表   item_inspectionCriteria  cust  storage_current_info
        Item item = itemMapper.selectById(itemId);
        if (item == null) {
            return null;
        }
        //item
        ItemStorageInfo info = new ItemStorageInfo();
        info.setItemId(item.getId());
        BeanUtils.copyProperties(item, info);

        //库存
        QueryWrapper<StorageCurrentInfo> query = new QueryWrapper<>();
        query.eq("itemId", itemId).eq("storageType", storageType);
        List<StorageCurrentInfo> storage = list(query);
        if (storage == null || storage.size() == 0) {
            info.setAllocatableSize(0);
            info.setSize(0);
            info.setUpperLimit(0);
            info.setLowerLimit(0);
            info.setReceiveUpperLimit(0);
            info.setCustName("");
            info.setStatus(StorageStatusEnum.BZ);
        } else {
            StorageCurrentInfo storageCurrentInfo = storage.get(0);
            info.setAllocatableSize(storageCurrentInfo.getAllocatableSize());
            info.setSize(storageCurrentInfo.getSize());
            info.setUpperLimit(storageCurrentInfo.getUpperLimit());
            info.setLowerLimit(storageCurrentInfo.getLowerLimit());
            info.setReceiveUpperLimit(storageCurrentInfo.getReceiveUpperLimit());
            info.setStatus(storageCurrentInfo.getStatus());
            if (storageType == 2) {
                QueryWrapper<PurchaseRecord> purQuery = new QueryWrapper<>();
                purQuery.eq("itemId", itemId);
                List<PurchaseRecord> list = iPurchaseRecordService.list(purQuery);
                purQuery.isNotNull("supplierName");
                if (list != null && list.size() > 0) {
                    info.setCustName(list.get(0).getSupplierName());
                } else {
                    info.setCustName("");
                }
            } else {
                Cust cust = orderItemMapper.getCustInfoByItemId(itemId);
                if (cust != null) {
                    info.setCustName(cust.getEnterpriseName());
                } else {
                    info.setCustName("");
                }
            }
        }

        //检验规则
        QueryWrapper<ItemInspectioncriteria> inspectionQuery = new QueryWrapper<>();
        inspectionQuery.eq("itemId", itemId);
        List<ItemInspectioncriteria> list = iItemInspectioncriteriaService.list(inspectionQuery);
        if (list != null) {
            info.setItemInspectioncriteria(list);
        } else {
            info.setItemInspectioncriteria(new ArrayList<>());
        }

        //入库详情
        QueryWrapper<StorageRecord> storageRecordQueryWrapper = new QueryWrapper<>();
        storageRecordQueryWrapper.eq("itemId", itemId);
        storageRecordQueryWrapper.eq("storageType", storageType);
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(3);
        integers.add(4);
        storageRecordQueryWrapper.in("status", integers);
        List<StorageRecord> storageRecords = storageRecordMapper.selectList(storageRecordQueryWrapper);
        ArrayList<InStorageInfo> inStorageInfos = new ArrayList<>();
        for (StorageRecord storageRecord : storageRecords) {
            Long storageRecodeId = storageRecord.getId();
            InStorageInfo inStorageInfo = new InStorageInfo();
            inStorageInfo.setInTime(storageRecord.getUpdateTime());
            inStorageInfo.setSize(storageRecord.getSize());
            inStorageInfo.setStatus(storageRecord.getStatus());
            inStorageInfo.setStorageRecodeId(storageRecord.getId());
            if (storageType == 2) {
                inStorageInfo.setCustName(iPurchaseRecordService.getById(storageRecord.getPurchaseRecordId()).getSupplierName());
            } else {
                inStorageInfo.setCustName(orderItemMapper.getOneByOrderIdAndItemId(storageRecord.getOrderId(), itemId).getCustName());
            }

            AddStorageInRecordReq result = new AddStorageInRecordReq();
            QueryWrapper<StorageInspection> inQu = new QueryWrapper<>();
            inQu.eq("storageRecodeId", storageRecodeId);
            List<StorageInspection> storageList = iStorageInspectionService.list(inQu);


            StorageInspection storageInspection = storageList.get(0);

            QueryWrapper<StorageInspectionRecord> recordQu = new QueryWrapper<>();
            recordQu.eq("storageRecodeId", storageRecodeId);
            List<StorageInspectionRecord> listrecord = iStorageInspectionRecordService.list(recordQu);


            result.setStorageRecodeId(storageRecodeId);
            result.setDetermine(storageInspection.getDetermine());
            result.setRemark(storageInspection.getRemark());
            result.setImgs(storageInspection.getImgs());

            result.setStorageInspectionRecords(listrecord);
            info.setStorageRecords(result);
        }

        return info;
    }

    @Override
    public boolean updateSize(Long recordId, Integer jj) {
        //获取入库明细
        StorageRecord storageRecord = storageRecordMapper.selectById(recordId);
        //获取物料id
        Long itemId = storageRecord.getItemId();
        //获取采购id  可能为null
        Long purchaseRecordId = storageRecord.getPurchaseRecordId();
        Long orderId = storageRecord.getOrderId();

        //原料入库
        if (purchaseRecordId != null) {
            StorageCurrentInfo storageCurrentInfo = storageCurrentInfoMapper.getByItemId(itemId, StorageType.YLK.getCode());
            PurchaseRecord purchaseRecord = iPurchaseRecordService.getById(purchaseRecordId);
            Long purchaseId = purchaseRecord.getPurchaseId();
            Purchase purchase = purchaseMapper.selectById(purchaseId);
            //获取采购类型  合同采购还是备料采购
            PurchaseTypeEnum purchaseType = purchase.getPurchaseType();

            UpdateWrapper<StorageCurrentInfo> update = new UpdateWrapper<>();
            update.eq("itemId", itemId).eq("storageType", StorageType.YLK.getCode());
            int totalNum = 0;
            //1.合同订单2.备料订单
            if (purchaseType == PurchaseTypeEnum.HTDD) {

                if (jj == 1) {
                    int i = storageCurrentInfo.getSize() + storageRecord.getSize();
                    totalNum = i + storageCurrentInfo.getAllocatableSize();
                    update.set("size", i);
                    //修改之前orderItem可能是原料不足的状态
                    OrderItem oneByOrderIdAndItemId = orderItemMapper.getOneByOrderIdAndItemId(purchase.getObjId(), purchaseRecord.getItemId());
                    if (oneByOrderIdAndItemId != null) {
                        if (OrderItemStatusEnum.YLBZ.equals(oneByOrderIdAndItemId.getStatus())) {
                            orderItemMapper.updateStatus(oneByOrderIdAndItemId.setStatus(OrderItemStatusEnum.DFP));
                            Order order = orderMapper.selectById(purchase.getObjId());
                            if (order != null) {
                                OrderStatusEnum status = order.getStatus();
                                if (OrderStatusEnum.YLBZ.equals(status)) {
                                    order.setStatus(OrderStatusEnum.DFP);
                                    orderMapper.updateById(order);
                                }
                            }
                        }
                    }
                } else {
                    int i = storageCurrentInfo.getSize() - storageRecord.getSize();
                    i = i < 0 ? 0 : i;
                    totalNum = storageCurrentInfo.getAllocatableSize() + i;
                    update.set("size", i);
                }
            } else {//备料采购  + allocatablesize

                if (jj == 1) {
                    int i = storageCurrentInfo.getAllocatableSize() + storageRecord.getSize();
                    update.set("allocatableSize", i);
                    totalNum = i + storageCurrentInfo.getSize();
                } else {
                  int  i = storageCurrentInfo.getAllocatableSize() + storageRecord.getSize();
                    i = i < 0 ? 0 : i;
                    totalNum = i + storageCurrentInfo.getSize();
                    update.set("allocatableSize", i < 0 ? 0 : i);
                }
            }
            update.set("status", CommonUtils.getStorageStatus(totalNum , storageCurrentInfo.getUpperLimit(), storageCurrentInfo.getLowerLimit()).getCode());

            return update(update);
        }

        //成品入库/出库
        if (orderId != null) {
            StorageCurrentInfo storageCurrentInfo = storageCurrentInfoMapper.getByItemId(itemId, StorageType.CPK.getCode());
            OrderItem oneByOrderIdAndItemId = orderItemMapper.getOneByOrderIdAndItemId(orderId, itemId);

            UpdateWrapper<StorageCurrentInfo> update = new UpdateWrapper<>();
            update.eq("itemId", itemId).eq("storageType", StorageType.CPK.getCode());
            int totalSize = 0;
            if (oneByOrderIdAndItemId.getPurpose() == 1) {//订单的 + allocatableSize
                if (jj == 1) {
                    update.set("allocatableSize", storageCurrentInfo.getAllocatableSize() + storageRecord.getSize());
                    totalSize = storageCurrentInfo.getSize() + storageCurrentInfo.getAllocatableSize() + storageRecord.getSize();
                } else {
                    int i = storageCurrentInfo.getSize() - storageCurrentInfo.getAllocatableSize();
                    i = i < 0 ? 0 : i;
                    update.set("allocatableSize", i);
                    totalSize = i + storageRecord.getSize();
                }
            } else {//用于生产的
                if (jj == 1) {
                    update.set("size", storageCurrentInfo.getSize() + storageRecord.getSize());
                    totalSize = storageCurrentInfo.getSize() + storageRecord.getSize() + storageCurrentInfo.getAllocatableSize();
                    //修改之前可能原料不足的状态
                    List<Long> orderItemsByOrderIdAndMaterialId = orderMapper.getOrderItemsByOrderIdAndMaterialId(orderId, storageCurrentInfo.getItemId());
                    QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
                    orderItemQueryWrapper.in("id", orderItemsByOrderIdAndMaterialId);
                    List<OrderItem> orderItems = orderItemMapper.selectList(orderItemQueryWrapper);
                    for (OrderItem orderItem : orderItems) {
                        if (OrderItemStatusEnum.YLBZ.equals(orderItem.getStatus())) {
                            orderItemMapper.updateStatus(orderItem.setStatus(OrderItemStatusEnum.DFP));
                            Order order = orderMapper.selectById(orderId);
                            if (order != null) {
                                OrderStatusEnum status = order.getStatus();
                                if (OrderStatusEnum.YLBZ.equals(status)) {
                                    order.setStatus(OrderStatusEnum.DFP);
                                    orderMapper.updateById(order);
                                }
                            }
                        }
                    }
                } else {
                    int i = storageCurrentInfo.getSize() - storageRecord.getSize();
                    i = i < 0 ? 0 : i;
                    update.set("size", i);
                    totalSize = i + storageCurrentInfo.getAllocatableSize();
                }
            }
            update.set("status", CommonUtils.getStorageStatus(totalSize , storageCurrentInfo.getUpperLimit(), storageCurrentInfo.getLowerLimit()).getCode());
            return update(update);
        }

        return false;
    }
}
